<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="派工号" prop="docNum">
        <el-input
          v-model="queryParams.docNum"
          placeholder="请输入派工号模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="queryParams.dtDocStart"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="起始日期"
          end-placeholder="截止日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="queryParams.dtDocFinish"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="起始日期"
          end-placeholder="截止日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:dispatch:add']"
        >新增
        </el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:dispatch:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:dispatch:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:dispatch:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dispatchList" :highlight-current-row="true" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.docNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
              <span>{{ props.row.confirmUserName }}</span>
            </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="props.row.oaDictConfirmStatus"/>
            </el-form-item>
            <el-form-item label="审核时间：">
              <span>{{ props.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ props.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="下达时间" align="center" prop="docDt" width="150" />
      <el-table-column label="派工号" align="center" prop="docNum" width="150"/>
      <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="物料编码" align="center" prop="itemNum" width="160"/>
      <el-table-column label="规格" align="center" prop="itemSpecification" width="120"/>
      <el-table-column label="数量" align="center" prop="dispatchQty" width="80"/>
      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="dtStart" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dtStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成日期" align="center" prop="dtDone" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dtDone, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="计划号" align="center" prop="mpsDocNum" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="show_mesPs(scope.row)"
          >{{scope.row.mpsDocNum}}<i class="el-icon-caret-right"></i>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="工段" align="center" prop="deptName" width="120"/>
      <el-table-column label="经办人" align="center" prop="attentionNickName" width="120"/>

      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="已完成" align="center" prop="sysYesNoDone" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoDone"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:dispatch:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:dispatch:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='editing'">删除
          </el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                       v-hasPermi="['com:dropdown:more']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="showDialog_confirm" icon="el-icon-circle-check"
                                v-hasPermi="['oa:confirm:edit']"
                                :disabled="scope.row.oaDictConfirmStatus !='waiting'">审核
              </el-dropdown-item>
              <el-dropdown-item command="show_dialog_work" icon="el-icon-share"
                                v-hasPermi="['erp:ps:dispatch']"
                                :disabled="scope.row.oaDictConfirmStatus !='pass'">派工
              </el-dropdown-item>
              <el-dropdown-item command="setDone" icon="el-icon-s-flag"
                                v-hasPermi="['com:single:done']">完成
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改派工单管理对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-alert v-show="form.oaDictConfirmStatus != 'editing'"
                  style="margin-bottom: 15px;"
                  :title="form.latestTaskInfo"
                  type="info"
                  :closable="false"
                  effect="dark"
        >
        </el-alert>

        <el-row>



          <el-form-item label="车间计划" prop="fkMesPsUuid">
            <el-input v-model="form.fkMesPsUuid"  v-show="false"/>
            <el-input placeholder="请点击右侧按钮选择车间计划"
                      v-model="form.selectedMesPs"
                      class="input-with-select"
                      :style="{width: '100%'}"

                      readOnly="true"
            >
              <el-button type="info" plain
                         @click="dialog_show_selectMesPs"
                         slot="append"
                         icon="el-icon-search" ></el-button>
            </el-input>
          </el-form-item>

          <el-col :span="12">
            <el-form-item label="单据编号" prop="docNum">
              <el-input v-model="form.docNum" placeholder="请输入单据编号"/>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="物料名称">
              <span>{{ this.form.itemName }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="物料名称">
              <span>{{ this.form.itemName }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工段" prop="fkDeptId">
              <el-select
                filterable
                v-model="form.fkDeptId"
                placeholder="请选择车间"
                clearable
                style="width: 300px">
                <el-option
                  v-for="item in deptList"
                  :key="item.fkDeptId"
                  :label="item.deptName"
                  :value="item.fkDeptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="dispatchQty">
            <span slot="label">
                    数量
                   <el-tooltip content="计划投放数量" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
              <el-input v-model="form.dispatchQty" placeholder="请输入数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="fkAttentionUserId">
              <el-input v-model="form.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择经办人" v-model="form.selectedAttentionUser" class="input-with-select">
                <el-button @click="showDialog_selectDispatchAttentionUserName(form)" :style="{width: '100%'}"
                           slot="append"
                           icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="dtStart">
              <el-date-picker clearable
                              v-model="form.dtStart"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择开始时间"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="dtDone">
              <el-date-picker clearable
                              v-model="form.dtDone"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择结束时间"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="下达时间" prop="docDt">
              <el-date-picker clearable
                              v-model="form.docDt"
                              type="datetime"
                              placeholder="选择结束时间"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="docNote">
              <el-input v-model="form.docNote" placeholder="请输入备注" :style="{width: '100%'}" type="textarea"
                        autosize/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
        <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审
        </el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 派工（新增加工单） -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="dialog_title_work" :visible.sync="dialog_visible_work" width="1000px"
               append-to-body :close-on-click-modal=false>
      <el-form ref="form_work" :model="form_work" :rules="rules_work" label-width="100px">

        <el-input v-model="form_work.fkMesDispatchUuid" v-show="false"/>

        <el-tabs type="border-card" class="mb20">
          <el-tab-pane label="加工单信息">
            <el-row>

              <el-col :span="12">
                <el-form-item label="工序" prop="fkMesProcessExecDetailUuid">
                  <el-input v-model="form_work.fkMesProcessExecDetailUuid" v-show="false"/>
                  <el-input placeholder="请点击右侧按钮选择工序"
                            v-model="form_work.selectedProcessExecDetail"
                            class="input-with-select"
                            :style="{width: '100%'}"
                            >
                    <el-button type="info" plain
                               @click="showDialog_selectProcessExecDetail"
                               slot="append"
                               icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item prop="quotaQtyMin">
                  <span slot="label">
                    标准定额
                   <el-tooltip content="工艺施工中的定额（单位：分钟）只读" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>

                  <el-input placeholder="请先选择工序" v-model="form_work.quotaQtyMin" readOnly>
                    <template slot="append">分钟</template>
                  </el-input>

                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item prop="workQty" label="数量">
                  <el-input-number v-model="form_work.workQty"  placeholder="请输入数量" :style="{width:'100%'}" @input="inputChange"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="加工号" prop="docNum">
                  <el-input v-model="form_work.docNum" placeholder="请输入加工单单据编号"/>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="单据时间" prop="docDt">
                  <el-date-picker clearable size="small"
                                  v-model="form_work.docDt"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm"
                                  placeholder="选择单据时间"
                                  :style="{width: '100%'}" clearable>
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item prop="fkAttentionUserId">
                  <span slot="label">经办人
                    <el-tooltip content="括号内数字为用户ID"><i class="el-icon-question"></i></el-tooltip>
                  </span>
                  <el-input v-model="form_work.fkAttentionUserId" v-show="false"/>
                  <el-input placeholder="请选择经办人" v-model="form_work.attentionUserName" class="input-with-select">
                    <el-button @click="showDialog_selectAttentionUser( form_work )" slot="append"
                               icon="el-icon-search"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item prop="totalQuotaQtyMin">
                  <span slot="label">
                    总定额
                   <el-tooltip content="总定额：单位定额*数量，不用填写，自动带出" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>

                  <el-input placeholder="请先选择工序" v-model="form_work.totalQuotaQtyMin" readOnly>
                    <template slot="append">分钟</template>
                  </el-input>
                </el-form-item>

              </el-col>
            </el-row>

          </el-tab-pane>
          <el-tab-pane label="备注信息">

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="docNote">
                  <el-input v-model="form_work.docNote"
                            type="textarea"
                            autosize
                            placeholder="请输入备注内容"
                            :style="{width: '100%'}"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>

        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span><b>作业员工</b></span>
          </div>

          <el-row class="mb10">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="add_worker">添加</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="remove_workers">删除</el-button>
          </el-row>

          <el-table :data="form_work.mesWorkWorkersList" @selection-change="selectionChange_workers"
                    ref="form_work.mesWorkWorkersList">

            <el-table-column type="selection" width="50" align="center"
                             :disabled="form_work.oaDictConfirmStatus != 'editing'"/>
            <el-table-column label="排序序号" prop="orderNum" align="center" width="">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderNum" placeholder="请输入排序序号"/>
              </template>
            </el-table-column>

            <el-table-column label="员工姓名" prop="workerName" align="center" width="400">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fkUserIdWorker" v-show="false"/>
                <el-input placeholder="请选择员工" v-model="scope.row.workerName"
                          class="input-with-select">
                  <el-button @click="showDialog_selectWorker(scope)" slot="append" icon="el-icon-search"></el-button>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="标准定额（分钟）" prop="quotaWorkingHours" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.quotaWorkingHours" placeholder="请输入工时"/>
              </template>
            </el-table-column>
          </el-table>

        </el-card>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_work">确 定</el-button>
        <el-button @click="hideDialog_work">取 消</el-button>
      </div>
    </el-dialog>


    <select-process-exec-detail ref="component_selectProcessExecDetail" @ok="selectProcessExecDetail_done"/>
    <select-user ref="component_selectAttentionUser" @ok="selectAttentionUser_done"/>
    <select-user ref="component_selectDispatchAttentionUserName" @ok="selectDispatchAttentionUserName_done"/>
    <select-user ref="component_selectWorker" @ok="selectWorker_done"/>
    <select-mesPs ref="component_selectMesPs" @ok="selectMesPs_done"/>
    <confirm ref="component_confirm" @ok="confirm_done()"/>

  </div>
</template>

<script>
  import {listDispatch, getDispatch, delDispatch, addDispatch, updateDispatch} from "@/api/mes/dispatch";
  import {addWork} from "@/api/mes/work";

  import selectProcessExecDetail from "../processExecDetails/selectProcessExecDetail";

  import {newDocNum} from "@/api/oa/docNum";
  import {parseTime} from "@/utils/ruoyi";
  import confirm from "../../oa/confirm";

  import selectMesPs from "../../mes/ps/selectMesPs";
  import selectUser from "../../comn/userGroup/selectUser";
  import {getInfo} from "@/api/login";
  import {listDeptGroup} from "@/api/comn/deptGroup";

  export default {
    name: "Dispatch",
    dicts: ['sys_normal_disable', 'oa_dict_confirm_status', 'wms_dict_measuring_unit', 'sys_yes_no'],
    components: {selectUser, selectProcessExecDetail, confirm,selectMesPs},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 派工单管理表格数据
        dispatchList: [],
        checkedMesDispJobWorkers: [],
        deptList: [],
        // 弹出层标题
        title: "",
        currUser: null,
        // 是否显示弹出层
        open: false,
        dialog_visible_dispatch: false,
        dialog_visible_work: false,
        dialog_title_work: '',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fkMesPsUuid: null,
          fkDeptId: null,
          dispatchQty: null,
          dtStart: null,
          dtDone: null,
          sysNormalDisable: null,
          docTitle: null,
          docNum: null,
          docDt: null,
          docNote: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
          mesDictMeasuringUnit: null
        },
        // 表单参数
        form: {},
        form_work: {
          topAlertTitle: '提醒信息！',
          docNum: '提醒信息！',
          processExecUuid: '123',
          selectedProcessExecDetail: '',
          quotaQtyMin: '（请选择工序）',
          fkMesDispatchUuid: '',
          mesWorkWorkersList: [],
        },
        // 表单校验
        rules_work: {
          fkMesDispatchUuid: [
            {required: true, message: "派工外键不能为空", trigger: "blur"}
          ],
          fkMesProcessExecDetailUuid: [
            {required: true, message: "工序id不能为空", trigger: "change"}
          ],
          workQty: [
            {required: true, message: "数量不能为空", trigger: "blur"}
          ],
          sysNormalDisable: [
            {required: true, message: "状态不能为空", trigger: "change"}
          ],
          docNum: [
            {required: true, message: "单据编号不能为空", trigger: "blur"}
          ],
          docDt: [
            {required: true, message: "单据时间不能为空", trigger: "blur"}
          ],
          fkAttentionUserId: [
            {required: true, message: "经办人ID不能为空", trigger: "change"}
          ],
          oaDictConfirmStatus: [
            {required: true, message: "审核状态不能为空", trigger: "change"}
          ],
          createBy: [
            {required: true, message: "创建者不能为空", trigger: "blur"}
          ],
          createTime: [
            {required: true, message: "创建时间不能为空", trigger: "blur"}
          ],
        },
        rules: {
          fkMesPsUuid: [
            {required: true, message: "车间计划不能为空", trigger: "change"}
          ],
          fkDeptId: [
            {required: true, message: "工段不能为空", trigger: "change"}
          ],
          docNum: [
            {required: true, message: "单据编号不能为空", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "经办人不能为空", trigger: "change"}
          ],
          dtStart: [
            {required: true, message: "开始时间不能为空", trigger: "change"}
          ],
          dtDone: [
            {required: true, message: "结束时间不能为空", trigger: "change"}
          ],
          docDt: [
            {required: true, message: "下达时间不能为空", trigger: "change"}
          ],
          dispatchQty: [
            {required: true, message: "数量不能为空", trigger: "change"}
          ],
          createBy: [
            {required: true, message: "创建者不能为空", trigger: "blur"}
          ],
          createTime: [
            {required: true, message: "创建时间不能为空", trigger: "blur"}
          ],
        }
      };
    },
    created() {

      // $route params
      let dispatchDocNum = this.$route.params && this.$route.params.dispatchDocNum;
      if (dispatchDocNum) {
        this.queryParams.docNum = dispatchDocNum
      }else console.log('！！！ 无参数 ！！！')


      this.getList();
      this.getList_dept()
      getInfo().then(response => {
        this.currUser = response.user
      });

    },
    methods: {
      inputChange() {
        console.log(this.form_work.workQty)
        console.log(this.form_work.quotaQtyMin)
        if (this.form_work.quotaQtyMin == undefined) {
          this.form_work.quotaQtyMin = 0
        }
        this.form_work.totalQuotaQtyMin = this.form_work.workQty * this.form_work.quotaQtyMin
      },

      // 表单重置
      resetForm_work() {
        this.form_work = {
          mesWorkUuid: null,
          fkMesDispatchUuid: null,
          fkMesProcessExecDetailUuid: null,
          quotaWorkingHours: null,
          sysNormalDisable: null,
          workQty: null,
          docTitle: null,
          docNum: null,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          docNote: null,
          fkAttentionUserId: this.currUser.userId,
          attentionUserName: `${this.currUser.nickName}（${this.currUser.userId}）`,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          mesWorkWorkersList: [],
        };
        this.mesWorkWorkersList = [];
        this.resetForm("form");
      },

      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        console.log(row)
        let obj = {
          tableName: 'mes_dispatch',
          uuidColumn: 'dispatch_uuid',
          fkUuid: row.dispatchUuid,
          attentionUserNickName: row.attentionNickName,
          oaDictConfirmStatus: row.oaDictConfirmStatus,
          msg: `请审核派工单, 派工号：${row.docNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);

      },

      confirm_done() {

        this.getList()
      },

      show_dialog_work(row) {

        console.log(row)
        this.resetForm_work()

        this.dialog_visible_work = true
        this.dialog_title_work = '派工（新增加工单）'

        this.form_work.fkMesDispatchUuid = row.dispatchUuid
        this.form_work.workQty = row.dispatchQty
        newDocNum({preCode: 'WRK-', len: 12}).then(response => {
          this.form_work.docNum = response.msg
        })

        this.$refs.component_selectProcessExecDetail.processExecUuid = row.processExecUuid

      },

      hideDialog_work() {
        this.dialog_visible_work = false
      },

      /** 添加工人 */
      add_worker() {
        let obj = {
          orderNum: '1',
          fkUserIdWorker: '',
          workerName: '',
          quotaWorkingHours: '0',
        };
        this.form_work.mesWorkWorkersList.push(obj);
      },

      /** 删除工人（多人） */
      remove_workers() {
        if (this.checkedMesDispJobWorkers.length == 0) {
          this.$modal.msgError("请先选择要删除的完工汇报（工人）数据");
        } else {
          const mesDispJobWorkersList = this.form_work.mesWorkWorkersList;
          const checkedMesDispJobWorkers = this.checkedMesDispJobWorkers;
          this.form_work.mesWorkWorkersList = mesDispJobWorkersList.filter(function (item) {
            return checkedMesDispJobWorkers.indexOf(item.index) == -1
          });
        }
      },

      /** 复选框 */
      selectionChange_workers(selection) {
        this.checkedMesDispJobWorkers = selection.map(item => item.index)
      },

      /** 提交按钮 */
      submitForm_work() {
        console.log('202112161009')
        this.$refs["form_work"].validate(valid => {
          if (valid) {

            addWork(this.form_work).then(response => {
              this.$modal.msgSuccess("派工成功");
              this.hideDialog_work()
            });
          }
        });
      },

      /** 提交按钮 */
      submitForm_work_waitingConfirm() {
      },

      /** 显示对话框：选择工序 */
      showDialog_selectProcessExecDetail(scope) {
        this.$refs.component_selectProcessExecDetail.show();
      },

      /** 显示对话框：选择工序 */
      selectProcessExecDetail_done(detail) {
        console.log(detail)
        this.form_work.fkMesProcessExecDetailUuid = detail.processExecDetailUuid
        this.form_work.quotaQtyMin = detail.quotaQtyMin
        this.form_work.totalQuotaQtyMin = this.form_work.workQty * this.form_work.quotaQtyMin
        this.form_work.selectedProcessExecDetail = `序号：${detail.orderNum} / 符号：${detail.mesDictProcessCode} / ` +
          `名称：${detail.mesDictProcessName} / 类型：${detail.mesDictProcessType}`
      },


      // 组件 - 选择用户

      /** 选择经办人 */
      showDialog_selectAttentionUser(form) {
        this.currentForm = form
        this.$refs.component_selectAttentionUser.userGroup = 'worker';
        this.$refs.component_selectAttentionUser.show();
      },

      /** 选择经办人 */
      showDialog_selectDispatchAttentionUserName(form) {
        this.currentForm = form
        // this.$refs.component_selectAttentionUser.userGroup = 'worker';
        this.$refs.component_selectDispatchAttentionUserName.show();
      },

      /** 显示对话框：选择工人 */
      showDialog_selectWorker(scope) {
        this.currRowScope = scope
        this.$refs.component_selectWorker.userGroup = 'worker';
        this.$refs.component_selectWorker.show();
      },

      /** 选择经办人 - 完成 */
      selectAttentionUser_done(user) {
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.attentionUserName = user.userNickNameAndId
      },


      /** 选择经办人 - 完成 */
      selectDispatchAttentionUserName_done(user) {
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.selectedAttentionUser = user.userNickNameAndId
      },

      /** 选择工人 - 完成 */
      selectWorker_done(user) {
        this.currRowScope.row.fkUserIdWorker = user.userId
        this.currRowScope.row.workerName = user.userNickNameAndId
      },

      /** 查询派工单管理列表 */
      getList() {
        this.loading = true;
        if (this.queryParams.dtDocStart) {
          this.queryParams.dtDocStartBegin = this.queryParams.dtDocStart[0]
          this.queryParams.dtDocStartEnd = this.queryParams.dtDocStart[1]
        } else {
          this.queryParams.dtDocStartBegin = null
          this.queryParams.dtDocStartEnd = null
        }
        if (this.queryParams.dtDocFinish) {
          this.queryParams.dtDocFinishBegin = this.queryParams.dtDocFinish[0]
          this.queryParams.dtDocFinishEnd = this.queryParams.dtDocFinish[1]
        } else {
          this.queryParams.dtDocFinishBegin = null
          this.queryParams.dtDocFinishEnd = null
        }
        listDispatch(this.queryParams).then(response => {
          this.dispatchList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      /** 列表: 部门（车间） */
      getList_dept() {
        listDeptGroup({comnDictDeptGroup: 'work_section'}).then(response => {
          this.deptList = response.rows;
          this.loading = false;
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      // 表单重置
      reset() {
        this.form = {
          dispatchUuid: null,
          fkMesPsUuid: null,
          fkDeptId: null,
          dispatchQty: null,
          dtStart: null,
          dtDone: null,
          sysNormalDisable: null,
          docTitle: null,
          docNum: null,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          docNote: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          mesDictMeasuringUnit: null,
          attentionNickName: null
        };
        this.resetForm("form");
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.dispatchUuid)
        this.docDts = selection.map(item => item.docDt)
        this.docNums = selection.map(item => item.docNum)
        this.single = selection.length !== 1
        this.oaDictConfirmStatus = selection.map(i => i.oaDictConfirmStatus)
        this.multiple =
          (this.oaDictConfirmStatus.indexOf('editing') > -1 && [...new Set(this.oaDictConfirmStatus)] == 'editing') ? false : true
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();

        newDocNum({preCode: 'DIS-', len: 12}).then(response => {
          this.form.docNum = response.msg
        })

        this.open = true;
        this.title = "添加派工单管理";
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const dispatchUuid = row.dispatchUuid || this.ids
        getDispatch(dispatchUuid).then(response => {
          this.form = response.data;
          console.log(this.form)
          this.form.selectedMesPs = `计划号：${this.form.mpsDocNum}`
          this.form.selectedAttentionUser = `${this.form.attentionNickName}(${this.form.fkAttentionUserId})`

          this.form.oaDictConfirmStatus =
            ('editing' == this.form.oaDictConfirmStatus || 'reject' == this.form.oaDictConfirmStatus)
              ? 'editing' : this.form.oaDictConfirmStatus


          if(row.oaDictConfirmStatus!='editing'||row.oaDictConfirmStatus!='reject'||this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'){
            this.form.latestTaskInfo='💡 该条记录审核状态为'+
              this.selectDictLabel(this.dict.type.oa_dict_confirm_status, row.oaDictConfirmStatus||this.oaDictConfirmStatus)+'状态'+','+'不能修改'
          }

          this.form.itemName = row.itemName
          this.form.itemNnum = row.itemNum
          this.form.itemSpecification = row.itemSpecification
          this.form.wmsDictMeasuringUnit = this.selectDictLabel(this.dict.type.wms_dict_measuring_unit, row.wmsDictMeasuringUnit)

          this.open = true;
          this.title = "修改派工单";
        });
      },

      /** 提交按钮 */
      submitForm(confirmStatus) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
            if (this.form.dispatchUuid != null) {
              updateDispatch(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addDispatch(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const dispatchUuids = row.dispatchUuid || this.ids;
        const docDts = row.docDt || this.docDts;
        const docNums = row.docNum || this.docNums;
        this.$modal.confirm('是否确认删除下达时间为"' + docDts + '",派工号为"' + docNums + '"的派工单？', '删除确认').then(function () {
          return delDispatch(dispatchUuids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },

      /** 导出按钮操作 */
      handleExport() {
        this.download('mes/dispatch/export', {
          ...this.queryParams
        }, `mes_dispatch.xlsx`)
      },

      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "showDialog_confirm":
            this.showDialog_confirm(row);
            break;
          case "show_dialog_work":
            this.show_dialog_work(row);
            break;
          case "setDone":
            let id = row.dispatchUuid

            this.$modal.confirm(`是否确认派工号为 ${row.docNum} 的派工单已完成？`, '完成确认').then(function () {
              // return delDispatch(id);
              let d = {
                dispatchUuid: id,
                sysYesNoDone: row.sysYesNoDone == 'Y' ? 'N' : 'Y'
              }

              return updateDispatch(d).then(response => {
              });

            }).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            }).catch(() => {
            });

            break;
          default:
            break;
        }
      },

      // 显示 - 销售号
      show_mesPs(r) {
        console.log(r)
        this.$router.push(`/mes/ps/docNum/${r.mpsDocNum}`);
      },


      /** 显示对话框：选择加工单 */
      dialog_show_selectMesPs() {
        this.$refs.component_selectMesPs.dialog_show_selectMesPs();
      },

      /** 选择生加工单完成 */
      selectMesPs_done(plan) {
        console.log(plan)
        this.form.fkMesPsUuid = plan.mesPsUuid
        this.form.selectedMesPs =
          `计划号：${plan.docNum}，计划时间：${plan.docDt}`
      },


    }
  };
</script>
